/*
	配件还回数量

*/
public without sharing class PartsReturnDetailsController {
    
	public String msg {get; private set;}
   	public Boolean isErr {get; private set;}
   	public Boolean isSuccess {get;private set ;}

   	public String backId {get;private set;}

   	public String dataJson {get;private set;}
    public String searchCompany {get; set;}
    public String companycombobox {get; private set;}
   	public String saveJson {get; set;}
   	public  PartsReturn__c pr {get;private set;}
    private boolean isNew;
    public  Boolean isDealer {get; private set;}
    public PartsReturnDetailsController() {
        backId = System.currentPageReference().getParameters().get('id');
        pr = new PartsReturn__c();
        isNew = false;
    }
    public PartsReturnDetailsController(ApexPages.StandardController stdController) {
        pr = new PartsReturn__c();
        backId = System.currentPageReference().getParameters().get('id');
         isNew = false;

    }
     public String getOptMap(Map<String,String> opts){
      
      List<Map<String,String>>  dList = new List<Map<String,String>>();
      for (String k : opts.keySet()) {
        Map<String ,String> dataMap = new Map<String,String>();
        dataMap.put('text',opts.get(k) );
        dataMap.put('id',k );
        dList.add(dataMap);
      }  
      
      return EncodingUtil.urlEncode(JSON.serialize(dList), 'UTF-8');
    }

    public void init(){

    	 try {
            if(String.isBlank(backId)){

            	
                backId = '';
                pr.OwnerId = UserInfo.getUserId();

                isNew = true;
            }else{
                pr = [select Id ,OwnerId ,Company__c,NotificationAssistantTime__c  from PartsReturn__c where Id =:backId];

               if(pr.NotificationAssistantTime__c != null ) throw new DmlException('已通知助理不能修改!');
            }
            User u  = [select Id , ClientCode__c from User where Id=:pr.OwnerId];
            isDealer = u.ClientCode__c != null;
            
            if(isDealer)pr.Company__c = 'MKSY'; 

            companycombobox = getOptMap(ImportObject.getPicklistValues('PartsReturn__c', 'Company__c', true));

            Map<String,Object> dataMap = new Map<String,Object>();
            dataMap.put('detail', getDetails());
            //dataMap.put('search', getSearch());

            dataJson= EncodingUtil.urlEncode(JSON.serialize(dataMap), 'UTF-8');
        }
        catch (Exception e) {
            isErr = true ;
            ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));
        }

    	
    }

    public void setNil(){
    	dataJson = '';
        searchCompany = '';
    }
    public void getSearch(){

    	List<ProductBean> tmp = new List<ProductBean>();
      
    	for ( PartsLendingDetails__c pld : [select Name,PartsLendingApplication__r.Name , LendingMargin__c,Product__c,Product__r.NCCode__c ,Product__r.Name ,Id,PartsLendingApplication__c   from PartsLendingDetails__c where LendingMargin__c  > 0  
    		and PartsLendingApplication__r.OwnerId =:pr.ownerId  and PartsLendingApplication__r.IsSycToNc__c = true and  PartsLendingApplication__r.InventoryOrganization__c =:searchCompany ]) {
        	
        	tmp.add(new ProductBean(pld));
    	}
        dataJson =  EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');

    }
    public List<ProductBean> getDetails(){
    	//获取 服务请求里的借出明细中 还未还回的明细
        //如果 存在明细 则 取明细
        List<ProductBean> tmp = new List<ProductBean>();
        System.debug('PartsReturnDetailsController=>'+backId);
        for (PartsReturnDetails__c prd  :[select Id,ReturnAccessories__c,ReturnAccessories__r.Name,ReturnAccessories__r.NCCode__c ,ReturnQuantity__c,Parts__c,Parts__r.LendingMargin__c,Parts__r.PartsLendingApplication__r.Name  
         from PartsReturnDetails__c where PartsReturn__c=: backId] ) {

        	tmp.add(new ProductBean(prd));
        }

        return tmp;

       
    }

    public void save(){
    	msg = '';
    	try {
            Map<String,Object>saveMap = (Map<String,Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));
    	    
            pr.Company__c = DataUtil.getStringValue(saveMap.get('company'));

            List<Object> saveList = (List<Object>) saveMap.get('datas');

    	    List<PartsReturnDetails__c> details = new List<PartsReturnDetails__c>();
    	    Set<String> esets = new Set<String>();
            Map<String,Decimal> restMap = new Map<String,Decimal>();
    	    for (Object o  :saveList ) {
    	    	Map<String,Object> mo = (Map<String,Object>)o;
    	    	PartsReturnDetails__c p = new PartsReturnDetails__c();
    	    	p.ReturnAccessories__c = DataUtil.getStringValue(mo.get('productId'));
    	    	p.Id = DataUtil.getStringValue(mo.get('detailId'));
    	    	p.ReturnQuantity__c = DataUtil.getDecimalValue(mo.get('returnnum'));
    	    	p.Parts__c = DataUtil.getStringValue(mo.get('lendingId'));
    	    	if(p.Id == null && !isNew)p.PartsReturn__c = backId;
    	    	if(p.Id != null)esets.add(p.Id);
                restMap.put(p.Parts__c, p.ReturnQuantity__c == null ? 0 : p.ReturnQuantity__c);

    	    	details.add(p);
    	    }
           //保存之前验证是否超过实际借出
            Map<Id,Decimal>qMap = new Map<Id,Decimal>();
            for(PartsReturnDetails__c wp:[select Parts__c ,Id,ReturnQuantity__c from PartsReturnDetails__c where Parts__c in:restMap.keySet() and Id not in: esets]){

                Decimal q = wp.ReturnQuantity__c == null ? 0 : wp.ReturnQuantity__c;
                q =  q + ( qMap.containsKey(wp.Parts__c) ?qMap.get(wp.Parts__c) : 0) ;

                qMap.put(wp.Parts__c,q);

            }
            List<String> cerrors = new List<String>();
            //保存之前去验证是否有余量
            List<String> errors = new List<String>();
            for(PartsLendingDetails__c pd : [select Id,Name,LendingMargin__c,B_No__c from PartsLendingDetails__c where Id in:restMap.keySet()]){
                if(restMap.containsKey(pd.Id)){
                    
                    if((restMap.get(pd.Id) == null ? 0 :restMap.get(pd.Id))  > (pd.LendingMargin__c == null ? 0: pd.LendingMargin__c)  )errors.add(pd.Name+':'+pd.LendingMargin__c );
                    if(pd.B_No__c == null || pd.B_No__c < (restMap.get(pd.Id)+(qMap.containsKey(pd.Id) ? qMap.get(pd.Id) : 0  )  ))cerrors.add(pd.Name+':'+pd.LendingMargin__c );
                    restMap.remove(pd.Id);
                }
            }
            if(!cerrors.isEmpty() )msg = '下列配件申请使用超过借出数量:'+String.join(cerrors, ',');
            if(String.isNotBlank(msg)  )return;
            if(!errors.isEmpty())msg = '下列配件还回都超过配件剩余量:'+String.join(errors, ',');
            if(String.isNotBlank(msg))return;
            if(!restMap.isEmpty()) msg = '异常配件还回:'+JSON.serialize(restMap.keySet());
            if(String.isNotBlank(msg))return;

    	    SavePoint sp = Database.setSavepoint();
    	    try {
    	        if(isNew)pr.Id = null;
                upsert pr;
    	        delete [select Id from PartsReturnDetails__c where Id not in: esets and PartsReturn__c=:backId ];
                for ( PartsReturnDetails__c p :details ) {
                    if(p.Id == null )p.PartsReturn__c = pr.Id;
                }
            
    	        if(!details.isEmpty())upsert details;



    	        isSuccess = true;
    	        msg = '保存成功!';
                backId = pr.Id;

    	    }
    	    catch (Exception e) {
    	    	Database.rollback(sp);
    	   		msg = '保存失败:'+e.getMessage() +e.getStackTraceString(); 
    	    }
    	    
    	}catch (Exception e) {
    	   msg = '保存失败:'+e.getMessage() +e.getStackTraceString(); 
    	}
    	

    }

    public class ProductBean{
    	public String productId;
    	public String productName;
        public String nccode;
        public String lendName;
    	
    	public Decimal returnnum;
    	public String detailId;

    	public Decimal num;
    	public String lendingId;

    	public ProductBean(PartsReturnDetails__c prd){
    		productId = prd.ReturnAccessories__c;
    		productName = prd.ReturnAccessories__r.Name;
            nccode = prd.ReturnAccessories__r.NCCode__c;
    		returnnum = prd.ReturnQuantity__c;
    		lendingId = prd.Parts__c ;
    		num = prd.Parts__r.LendingMargin__c  ;
            lendName = prd.Parts__r.PartsLendingApplication__r.Name ;


    	}

    	public ProductBean(PartsLendingDetails__c prd){
    		productId = prd.Product__c;
    		productName = prd.Product__r.Name;
            nccode = prd.Product__r.NCCode__c;
    		num = prd.LendingMargin__c;
    		lendingId = prd.Id;
            lendName = prd.PartsLendingApplication__r.Name ;
    	}
    }


}